package com.pzhuweb.sgblog.domain.utils;

import com.pzhuweb.sgblog.domain.entity.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

/**
 * @author 鄧浩奇
 * @classname SecurityUtils
 * @description
 * @since 2023/7/7 15:31
 **/

public class SecurityUtils {

    /*
     * 获取Authentication
     * */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /*
     * 获取用户
     * */
    public static LoginUser getLoginUser() {
//        System.out.println(getAuthentication().getPrincipal());
//        System.out.println(getAuthentication().getPrincipal().getClass());
        if (!(getAuthentication().getPrincipal() instanceof String))
            return (LoginUser) getAuthentication().getPrincipal();
        return null;
    }

    public static Long getUserID() {
        if (Objects.isNull(getLoginUser())) {
            return -1L;
        }
        return getLoginUser().getUser().getId();
    }


    public static boolean isAdmin() {
        Long id = Objects.requireNonNull(getLoginUser()).getUser().getId();
        return id != null && id.equals(1L);
    }
}
